package com.zhx.real.advice.advice;

import com.zhx.real.core.util.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author ：zhanghaixuan
 * @date ：Created in 2019-03-21 10:35
 * @description：用途:基础的返回信息处理类
 * @modified By：zhanghaixuan
 * @version: 1.0
 */
@RestControllerAdvice
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {

    /**
     * 判断响应是否去拦截
     * @param methodParameter 方法的参数
     * @param aClass
     * @return boolean
     */
    @Override
    @SuppressWarnings("all")
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // 判断是否有这个注解  有就不管了  类上有
        if(methodParameter.getAnnotatedElement().isAnnotationPresent(IgnoreResponseAdvice.class)) {
            return false;
        }
        // 判断是否有这个注解  有就不管了  方法上有
        if(methodParameter.getMethod().isAnnotationPresent(IgnoreResponseAdvice.class)) {
            return false;
        }

        return true;
    }

    /**
     * 对返回的结果进行处理
     * @param o 结果
     * @param methodParameter 参数
     * @param mediaType 类型
     * @param aClass
     * @param serverHttpRequest 请求
     * @param serverHttpResponse 结果
     * @return Object
     */
    @Override
    @Nullable
    @SuppressWarnings("all")
    public Object beforeBodyWrite(@Nullable Object o, MethodParameter methodParameter, MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {

        /**
         * swagger 特殊处理 直接放行
         */
        if(((ServletServerHttpRequest) serverHttpRequest).getServletRequest().getRequestURI().equals("/v2/api-docs")){
            return o;
        }

        Result<Object> commonResponse = new Result<Object>(0,"");

        if(o instanceof Result){
            commonResponse= (Result<Object>) o;
        }else{
            commonResponse.setData(o);
        }

        return commonResponse;
    }
}
